import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created by ospip on 2017/11/26.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class IDGenerator {
    // Client, Clerk, Board, Server
    int cnt = 0;
    int workerID = 0;
    long lastTime = 0;
    long current, ret;

    public IDGenerator(int worker) {
        workerID = worker & 0x3ff;
    }

    public IDGenerator() {
        try {
            workerID = Integer.parseInt(InetAddress.getLocalHost().getHostAddress().split("\\.")[3]) & 0x3ff;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            workerID = 0;
        }
    }

    public synchronized long generate() {
        current = System.currentTimeMillis();
        if (lastTime == current) {
            ++cnt;
            if (cnt >= 4096) {
                for (;;) {
                    current = System.currentTimeMillis();
                    if (current > lastTime) {
                        cnt = 0;
                        break;
                    }
                }
            }
        }
        else cnt = 0;
        ret = current << 22;
        ret |= workerID << 12;
        ret |= cnt & 0xfff;
        lastTime = current;
        return ret;
    }

    public String tell(long id) {
        long gTime = id >> 22;
        Date d = new Date(gTime);
        int worker = (int)(id >> 12) & 0x3ff;
        int cnt = (int)(id & 0xfff);
        return String.format("[ID %d][Time %s][Worker %d][Count %d]", id, d.toString(), worker, cnt);
    }

    public static void main(String[] args) {
        IDGenerator id = new IDGenerator();

        long[] ids = new long[10];
        for (int i = 0; i < 10; i++) {
            ids[i] = id.generate();
        }
        for (long i : ids) System.out.println(id.tell(i));
    }
}
